<template>
  <div class="text-editing operation-pop"
    ref="operationPop" :style="{height: textForm.fontColorOrBgColor.length > 0 ? '120px' : '80px'}">
    <div class="popover-arrow"></div>
       
    <div class="top">
      <a-select :class="`p_${props.uId}`" style="width: 180px" :value="textForm.fontFamily" @change="getFontFamily">
        <a-select-option v-for="(item, index) in fontFamilyData"
        :value="item.value" :key="index">
          <render-v-node :v-node="item.label"/>
        </a-select-option>
      </a-select>
    </div>

    <div class="center">
      
      <button :class="{active: isActive.bold}" @click.stop="setStyles({command: 'bold'})"  >
        <a-tooltip placement="topLeft">
          <template #title>
            <span>文本加粗</span>
          </template>
          <BoldOutlined  />
        </a-tooltip>
      </button>

      <button :class="{active: isActive.italic}"
        @click.stop="setStyles({command: 'italic'})">
        <a-tooltip placement="topLeft">
          <template #title>
            <span>文本倾斜</span>
          </template>
          <ItalicOutlined />
        </a-tooltip>
      </button>

      <button :class="{active: isActive.underline}"
      @click.stop="setStyles({command: 'underline'})">
        <a-tooltip placement="topLeft">
          <template #title>
            <span>下划线</span>
          </template>
          <UnderlineOutlined   />
        </a-tooltip>
      </button>

      <button :class="{active: textForm.fontColorOrBgColor === 'forecolor'}"
        @click.stop="setFontColorOrBgColor('forecolor')" >
        <a-tooltip placement="topLeft">
          <template #title>
            <span>文本颜色</span>
          </template>
          <FontColorsOutlined />
        </a-tooltip>
      </button>
      
      <button :class="{active: textForm.fontColorOrBgColor === 'backcolor'}"
        @click.stop="setFontColorOrBgColor('backcolor') ">
        <a-tooltip placement="topLeft">
          <template #title>
            <span>背景颜色</span>
          </template>
          <BgColorsOutlined style="font-size: 18px;" />
        </a-tooltip>
      </button>
    </div>

    <div class="bottom" :style="{height: textForm.fontColorOrBgColor.length > 0 ? '60px' : '0px'}">
      <z-color-picker defaultColor="#000" @change="getColor" />
    </div>
   
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { BoldOutlined, ItalicOutlined, UnderlineOutlined, FontColorsOutlined, BgColorsOutlined } from '@ant-design/icons-vue';
import { forOwn } from 'lodash';
import RenderVNode from '../common/RenderVNode'
import { fontFamilyOption } from '../../typescript/textConfig';

const fontFamilyData = [
  { label: '无', value: '' },
  ...fontFamilyOption
]

const props = defineProps<{uId: string}>()

interface TextForm {
  fontFamily: string,
  fontColorOrBgColor: string
}

const textForm = ref<TextForm>({
  fontFamily: '',
  fontColorOrBgColor: ''
})

const isActive = ref<{ bold: boolean, italic: boolean, underline: boolean }>({
  bold: false,
  italic: false,
  underline: false
})

const emit = defineEmits(['changeTextStyle'])

const setFontColorOrBgColor = (value: string) =>{
  if (textForm.value.fontColorOrBgColor.length === 0) {
    textForm.value.fontColorOrBgColor = value
    return
  }
  textForm.value.fontColorOrBgColor = ''
  setTimeout(() => {
    textForm.value.fontColorOrBgColor = value
  }, 500)
  
}

// 获取字体
const getFontFamily = (value: string) => {
  console.log('获取字体', value)
  textForm.value.fontFamily = value
  // emit('changeTextStyle', )
  setStyles({command: 'fontName', value})
}

const getColor = (value: string) => {
  setStyles({command: textForm.value.fontColorOrBgColor, value})
}

const setStyles = (data: {command: string, value?: string}) => {
  const { command, value } = data
  isActive.value[command] = !isActive.value[command]
  if (!document.execCommand(command, true, value)) {
    console.warn('命令执行失败！');
  } else {
    emit('changeTextStyle')
  }
}


onMounted(() => {
  if (props.uId) {
    document.querySelector(`.text-editing .ant-select-selection-search-input`)?.setAttribute('type', 'color')
    mouseMoveUp()
  }
})



// HTMLElement 类型表示 HTML 元素。在 TypeScript 中可以通过定义接口来添加额外的属性。
interface NewHTMLElement extends HTMLElement {
  face?: string; // 自定义属性名称为 "face"
}
 
let isShow:boolean = false
const operationPop = ref()
// 优化
const selection:Selection | null = window.getSelection()
const document:Document = window.document
const mouseMoveUp = () => {
  const contenteditableBox = document.getElementById(props.uId) as HTMLElement;
  contenteditableBox.addEventListener('mousemove', (e: MouseEvent) => {
    
    const { left, top } = contenteditableBox.getBoundingClientRect(); // 获取元素相对于视口左上角的位置信息
    const distanceX:number = e.clientX - (left + window.pageXOffset); // X轴距离
    const distanceY:number = e.clientY - (top + window.pageYOffset); // Y轴距离
    
    if (selection) {
      if (selection.toString().length === 0 && operationPop.value) {
        console.log('测试bug')
        operationPop.value.style.display = 'none'
        isShow = false
        forOwn(textForm.value, (value, key) => textForm.value[key] = ''); // 遍历并清空每个属性
        forOwn(isActive.value, (value, key) => delete isActive.value[key])
        // fontColorOrBgColor.value = ''
      }
    }
   
    const handleMouseup = () => {
      
      if (selection) {

        // console.log(selection)
        const { anchorNode, focusNode } = selection
        if (!anchorNode) {
          return
        }
        const { parentElement: anchorParentElement } = anchorNode as HTMLElement
        const { parentElement: focusParentElement } = focusNode  as NewHTMLElement
        
        if (selection.toString().length === 0) {
          console.log('没选中文本！',  selection.toString())
          operationPop.value.style.display = 'none'
          if (isShow) {
            forOwn(textForm.value, (value, key) => textForm.value[key] = '')
            forOwn(isActive.value, (value, key) => delete isActive.value[key])
          }
          isShow = false
          return
        }

        if (operationPop.value && !isShow) {
          if (anchorParentElement?.innerHTML === focusParentElement?.innerHTML) {
            textForm.value.fontFamily = focusParentElement?.getAttribute('face') || ''
            isActive.value.bold = focusParentElement?.localName === 'b'
            isActive.value.italic = focusParentElement?.localName === 'i'
            isActive.value.underline = focusParentElement?.localName === 'u'
          }
          
          console.log('block', selection.toString())
          operationPop.value.style.display = 'block'
          operationPop.value.style.left = distanceX + 2  + 'px'
          operationPop.value.style.top = distanceY + 10 + 'px'
          setTimeout(() =>{
            isShow = true
          }, 100)
        }
      }
      
      contenteditableBox.removeEventListener("mouseup", handleMouseup)
        
    }
      // document.removeEventListener('mousemove', handleMouseup)
  
      contenteditableBox.addEventListener("mouseup", handleMouseup)
    // console.log("鼠标与元素的水平距离为：" + distanceX);
    // console.log("鼠标与元素的垂直距离为：" + distanceY);
  })
} 


</script>

<style lang="scss">
@import "../../theme/styles/mixin.scss";
.text-editing {
  text-align: left;
  position: absolute;
  left: 0px;
  bottom: 0px;
  z-index: 11;
  background-color: yellow;
  display: none;
  background-color: #ffffff;
  background-clip: padding-box;
  border-radius: 8px;
  box-shadow: 0 6px 16px 0 rgba(0, 0, 0, 0.08),
  0 3px 6px -4px rgba(0, 0, 0, 0.12), 
  0 9px 28px 8px rgba(0, 0, 0, 0.05);
  padding: 3px;
  width: 220px;
  transition: all 0.5s;

  .top {
    margin-bottom: 6px;
  }
  .ant-select-selector  {
    border-radius: 4px !important;
  }

  .center {
    button:nth-child(2n) {
      margin: 5px 12px 0;
    }
    button {
      background: transparent;
      border: none;
      cursor: pointer;
      font-size: 16px;
      transition: none;
    }
    .active {
      color: #ffffff;
      @include bg_color;
      opacity: 0.6;
      border-radius: 555px;
    }
  }


  .bottom {
    position: absolute;
    bottom: -5px;
    left: 3px;
    overflow: hidden;
  }
 
  .popover-arrow {
    position: absolute;
    top: 0;
    left: 8px;
    transform: translateY(-100%);
    z-index: 11;
    display: block;
    pointer-events: none;
    width: 16px;
    height: 16px;
    overflow: hidden;
  }

  .popover-arrow::before {
    position: absolute;
    bottom: 0;
    inset-inline-start: 0;
    width: 16px;
    height: 8px;
    background: #ffffff;
    clip-path: polygon(1.6568542494923806px 100%, 50% 1.6568542494923806px, 14.34314575050762px 100%, 1.6568542494923806px 100%);
    /* clip-path: path('M 0 8 A 4 4 0 0 0 2.82842712474619 6.82842712474619 L 6.585786437626905 3.0710678118654755 A 2 2 0 0 1 9.414213562373096 3.0710678118654755 L 13.17157287525381 6.82842712474619 A 4 4 0 0 0 16 8 Z'); */
    content: "";
  }
  .popover-arrow::after {
    content: "";
    position: absolute;
    width: 8.9px;
    height: 8.9px;
    bottom: 0;
    inset-inline: 0;
    margin: auto;
    border-radius: 0 0 2px 0;
    transform: translateY(50%) rotate(-135deg);
    box-shadow: 3px 3px 7px rgba(0, 0, 0, 0.1);
    z-index: 0;
    background: transparent;
    
  }
    
  
}

</style>